package com.zzh.webhook.service;

import com.zzh.webhook.config.GitlabConfig;
import com.zzh.webhook.model.GitlabPushEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
@RequiredArgsConstructor
public class WebhookService {
    
    private final GitlabConfig gitlabConfig;
    private final GitService gitService;
    private final BuildService buildService;
    
    // 使用线程池处理构建请求，避免阻塞
    private final ExecutorService executorService = Executors.newFixedThreadPool(2);
    
    /**
     * 处理GitLab的Push Event webhook
     * 
     * @param event GitLab推送事件
     * @param token 请求中的Token
     * @return 处理结果
     */
    public String handlePushEvent(GitlabPushEvent event, String token) {
        // 验证Token
//        if (!validateToken(token)) {
//            log.warn("Invalid webhook token received");
//            return "Invalid token";
//        }
        
        // 检查分支是否匹配
        String branchName = event.getBranchName();
        if (!gitlabConfig.getWebhook().getBranch().equals(branchName)) {
            log.info("Ignoring push to branch: {}. Only monitoring branch: {}", 
                    branchName, gitlabConfig.getWebhook().getBranch());
            return "Ignored branch";
        }
        
        // 异步处理构建请求
        executorService.submit(() -> {
            try {
                processPushEvent(event);
            } catch (Exception e) {
                log.error("Error processing push event", e);
            }
        });
        
        return "Processing started";
    }
    
    /**
     * 验证webhook请求的Token
     * 
     * @param token 请求中的Token
     * @return 是否有效
     */
    private boolean validateToken(String token) {
        return gitlabConfig.getWebhook().getSecretToken() != null && 
               gitlabConfig.getWebhook().getSecretToken().equals(token);
    }
    
    /**
     * 处理推送事件
     * 
     * @param event GitLab推送事件
     */
    private void processPushEvent(GitlabPushEvent event) throws IOException {
        log.info("Processing push event from: {}, branch: {}", 
                event.getUserName(), event.getBranchName());
        
        // 初始化或更新本地仓库
        gitService.initOrUpdateRepository();
        
        // 切换到指定分支并拉取最新代码
        gitService.checkoutAndPull(event.getBranchName());
        
        // 收集所有修改的文件
        List<String> changedFiles = new ArrayList<>();
        for (GitlabPushEvent.Commit commit : event.getCommits()) {
            changedFiles.addAll(commit.getAdded());
            changedFiles.addAll(commit.getModified());
            changedFiles.addAll(commit.getRemoved());
        }
        
        // 构建受影响的模块
        buildService.buildAffectedModules(changedFiles);
    }
} 